package tech.jabari.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.jabari.user.entity.User;
import tech.jabari.user.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static tech.jabari.constants.UMSConstant.*;
import static tech.jabari.constants.UMSConstant.VERIFY_CODE;


@Controller
public class UpdateUserController {

    @Autowired
    private UserService userService;
    /**
     * 更新用户
     */
    @PostMapping("/doUpdateUser.action")
    @ResponseBody
    protected Map<String,Object> updateUser(User user, String code,
                              @RequestParam(name="headImgFile",required = false)
                                      MultipartFile headImg,
                              HttpServletRequest request, HttpSession session)
            throws IOException {
        System.out.println("---------doUpdateUser()... ");
        System.out.println("username = " + user.getUsername());
        System.out.println("pwd = " + user.getPwd());
        System.out.println("birth = " + user.getBirthStr());
        Map<String, Object> map = new HashMap<>();
        // 获取session中保存的正确的验证码。
        Object verifyCodeObj = session.getAttribute(VERIFY_CODE);
        if (verifyCodeObj != null) {
            String verifyCode = verifyCodeObj.toString();
            if (!verifyCode.equalsIgnoreCase(code)) {
                map.put(VERIFY_CODE,"-1");
                return map;
            } else {
                map.put(VERIFY_CODE,"1");
            }
        }
        // ""  ->  null
        if ("".equals(user.getBirthStr())) {
            user.setBirthStr(null);
        }
        //2.调用service，更新用户信息。
        int rest = userService.updateUser(user,headImg,request);
        System.out.println("update user result = " + rest);

        return map;
    }

    /**
     * 显示用户详情html页面
     * @throws IOException
     */
    @GetMapping({"/updateUser.action","/{id}/updateUser.action"})
    protected String viewUserDetail(@PathVariable(required = false) Integer id,HttpSession session)  {
        if (null == id/* && id.equals(-1)*/) {
            Object idObj = session.getAttribute(USER_ID);
            if (idObj != null) {
                id = (Integer) idObj;
            } else {
                return "redirect:"+ACCESS_DENY_URL;
            }
        }
        return("redirect: /detail.html?id=" + id);
    }
}
